<?php

namespace app\api\logic;

use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Dingtalk;

use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Models\GetAccessTokenRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use think\facade\Cache;
use think\facade\Log;

class BaseSDKLogic
{
    protected $runtimeOptions = '';
    public function __construct()
    {
        $this->runtimeOptions = new RuntimeOptions(['ignoreSSL' => true]);
    }

    private function authClient()
    {
        $config = new Config([]);
        $config->protocol = "https";
        $config->regionId = "central";
        return new Dingtalk($config);
    }

    // 获取
    protected function accessToken()
    {
        $configDing = \think\facade\Config::get('ding');
        $accessToken = Cache::get($configDing['AccessTokenKey']);
        if ($accessToken === null) {
            $client = $this->authClient();
            $getAccessTokenRequest = new GetAccessTokenRequest([
                "appKey" => $configDing['AppKey'],
                "appSecret" => $configDing['AppSecret']
            ]);
            //
//            $res = $client->getAccessToken($getAccessTokenRequest);

            $res = $client->getAccessTokenWithOptions($getAccessTokenRequest,[],$this->runtimeOptions);

            $accessToken = $res->body->accessToken;
            Cache::set($configDing['AccessTokenKey'],$accessToken,$res->body->expireIn - 200);
        }
        return $accessToken;
    }
}